import 'package:badges/badges.dart' as myBadges;
import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/constants.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/controller/evaluation.dart';
import 'package:ichinesereader/models/common/LevelOption.dart';
import 'package:ichinesereader/pages/common/levelStandards.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/utils/log.dart';
import '../../controller/books.dart';
import '../../models/book/BookSearchDto.dart';
import '../../themes/appTheme.dart';

class LevelChioceChipEvaluationWidget extends StatefulWidget {
  LevelChioceChipEvaluationWidget({
    Key? key,
  }) : super(key: key);

  @override
  State<LevelChioceChipEvaluationWidget> createState() =>
      _LevelChioceChipEvaluationWidgetState();
}

class _LevelChioceChipEvaluationWidgetState
    extends State<LevelChioceChipEvaluationWidget> {
  int selectedLevelOption = 0;
  final box = Hive.box('appconfig');
  final BooksController _booksController = Get.find();
  final EvaluationController _evaluationController = Get.find();

  @override
  void initState() {
    int _currentLevel = 1;
    try {
      _currentLevel =
          (box.get(CacheManagerKey['eveluationlevel'].toString()) as double)
              .toInt();
      selectedLevelOption = _currentLevel - 1;
    } catch (error) {}
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    Log.debug('build LevelChioceChipWidget');
    String classId = box.get(CacheManagerKey['currentclass'].toString());

    return myBadges.Badge(
      //shape: BadgeShape.square,
      badgeStyle: myBadges.BadgeStyle(
        badgeColor: Get.isDarkMode
            ? Get.theme.primaryColorDark
            : Colors.red.withOpacity(0.9),
      ),
      position: myBadges.BadgePosition.bottomEnd(bottom: 0, end: 3),
      badgeContent: GestureDetector(
        onTap: () {
          Get.to(() => LevelStandardsPage(isEvaluation: true));
        },
        child: Tooltip(
          message: 'Level Comparison Chart'.tr,
          child: Icon(
              const IconData(
                0xf04e5,
                fontFamily: 'MaterialIcons',
              ),
              //Icon(Icons.bubble_chart_outlined,
              color: Get.isDarkMode ? Colors.black : AppTheme.colors.lightPink,
              size: 15.0),
        ),
      ),
      child: Container(
        height: 45.0,
        child: ListView.builder(
          scrollDirection: Axis.horizontal,
          itemCount: Constants.levelEvaluationOptions.length,
          itemBuilder: ((context, index) {
            return Padding(
              padding: const EdgeInsets.symmetric(
                horizontal: 3.0,
              ),
              child: ChoiceChip(
                padding: EdgeInsets.symmetric(horizontal: 12.0),
                shape: BeveledRectangleBorder(
                  side: BorderSide(color: Colors.white, width: 0.3),
                  borderRadius: BorderRadius.circular(1.0),
                ),
                backgroundColor: hexStringToHexInt(
                  Constants.levelEvaluationOptions[index].color.toString(),
                ),
                label: Text(
                  Constants.levelEvaluationOptions[index].label
                      .toString()
                      .replaceAll('Level 0', 'N/A')
                      .replaceAll('Level ', ''),
                  style: TextStyle(
                      fontWeight: FontWeight.bold, color: Colors.white),
                ),
                selected: selectedLevelOption == index,
                selectedColor: Colors.black,
                onSelected: (selected) {
                  setState(
                    () {
                      selectedLevelOption = selected ? index : 0;
                    },
                  );

                  // if (value == false) return;
                  //     var item = value as LevelOption;
                  _evaluationController.fetchEvaluationBooks(
                      '0',
                      '0',
                      'EVALUATION',
                      Constants.levelEvaluationOptions[index].value
                          .toString()
                          .replaceAll('level', ''),
                      classId);

                  BookSearchDto dto = new BookSearchDto();
                  dto.proficiencyLevel = [];
                  List<String> levelstr = [];
                  List<LevelOption> levelEvaluationOptions = [];

                  var item = Constants.levelEvaluationOptions[index];
                  levelstr.add(item.value.toString());
                  levelEvaluationOptions.add(item);

                  _booksController.setBookSearchDto(dto);
                  _booksController.setLevelOptions(levelEvaluationOptions);
                  if (levelstr.length > 0) {
                    dto.proficiencyLevel?.addAll(levelstr);
                    _booksController.fetchSearchOpenLibraryBookItems(
                        Constants.pageLimit, 0, dto);
                  } else {
                    _booksController.fetchOpenReadingItems(
                        Constants.pageLimit, 0);
                  }
                },
              ),
            );
          }),
        ),
      ),
      // FormBuilderChoiceChip(
      //   spacing: 6.0,
      //   runSpacing: 3.0,
      //   alignment: WrapAlignment.start,
      //   selectedColor: Get.isDarkMode
      //       ? Colors.white
      //       : Get.theme.primaryColorDark.withOpacity(0.9),
      //   backgroundColor: Colors.transparent,
      //   initialValue: Constants.levelEvaluationOptions
      //       .where((element) =>
      //           element.value.toString().replaceAll('level', '') ==
      //           _currentLevel.toString())
      //       .first,
      //   decoration: InputDecoration(
      //     //labelText: 'Levels',
      //     labelStyle: Get.theme.textTheme.labelSmall,
      //     border: InputBorder.none,
      //   ),
      //   name: 'filter_chip',
      //   onChanged: (value) {
      //     if (value == null) return;
      //     var item = value as LevelOption;
      //     _evaluationController.fetchEvaluationBooks('0', '0', 'EVALUATION',
      //         item.value.toString().replaceAll('level', ''), classId);
      //   },
      //   options: Constants.levelEvaluationOptions
      //       .map((level) => FormBuilderChipOption<LevelOption>(
      //             value: level,
      //             child: Text(
      //               level.label
      //                   .toString()
      //                   .replaceAll('Level 0', 'N/A')
      //                   .replaceAll('Level ', ''),
      //               style: TextStyle(
      //                 fontSize: 15,
      //                 fontWeight: FontWeight.bold,
      //                 color: hexStringToHexInt(level.color.toString()),
      //                 letterSpacing: 0,
      //               ),
      //             ),
      //           ))
      //       .toList(),
      // ),
    );
  }
}
